//
//  UIColorExtension.swift
//  zhende
//
//  Created by chenliang on 2016/12/7.
//  Copyright © 2016年 chenliang. All rights reserved.
//
import UIKit

extension UIColor {
    
    convenience init?(hexString: String, alpha: Float = 1) {
        var hex = hexString
        
        if hex.hasPrefix("#") {
            hex = String(hex[hex.index(after: hex.startIndex)...])
        }
        
        if let _ = hex.range(of: "(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .regularExpression) {
            if hex.lengthOfBytes(using: String.Encoding.utf8) == 3 {
                let redHex = String(hex[hex.startIndex])
                let greenHex = String(hex[hex.index(after: hex.startIndex)])
                let blueHex = String(hex[hex.index(before: hex.endIndex)])
                hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
            }
            let redHex = String(hex[hex.startIndex...hex.index(after: hex.startIndex)])
            let greenHex = String(hex[hex.index(hex.startIndex, offsetBy: 2)...hex.index(hex.startIndex, offsetBy: 3)])
            let blueHex = String(hex[hex.index(hex.startIndex, offsetBy: 4)...hex.index(hex.startIndex, offsetBy: 5)])
            
            var redInt:   CUnsignedInt = 0
            var greenInt: CUnsignedInt = 0
            var blueInt:  CUnsignedInt = 0
            
            Scanner(string: redHex).scanHexInt32(&redInt)
            Scanner(string: greenHex).scanHexInt32(&greenInt)
            Scanner(string: blueHex).scanHexInt32(&blueInt)
            
            self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
        }
        else
        {
            self.init()
            return nil
        }
    }
    
    convenience init?(hex: Int, alpha: Float = 1) {
        let hexString = NSString(format: "%2X", hex)
        self.init(hexString: hexString as String, alpha: alpha)
    }
}
